package com.manong.bookstore.payment.controller;

import com.manong.common.utils.R;
import com.manong.bookstore.payment.entity.*;
import com.manong.bookstore.payment.feign.OrderFeignService;
import com.manong.bookstore.payment.feign.ProduceFeignService;
import com.manong.bookstore.payment.feign.ShoppingCartFeignService;
import com.manong.bookstore.payment.feign.UserFeignService;
import com.manong.bookstore.payment.service.BillService;
import com.manong.bookstore.payment.vo.ProduceVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("payment/confirm")
public class ConfirmController {

    @Autowired
    UserFeignService userFeignService;

    @Autowired
    ShoppingCartFeignService shoppingCartFeignService;

    @Autowired
    ProduceFeignService produceFeignService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    private BillService billService;

    /**
     * 传递购物车选中的商品
     * @param select
     * @param session
     * @return
     */
    /*@RequestMapping("/select")
    public R list(@RequestBody Integer[] select, HttpSession session){
        String string=session.getAttribute("userId")+"select";
        session.setAttribute(string,select);
        return R.ok();
    }*/

    /**
     * 获得用户的地址信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/info")
    public R info(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        System.out.println(userId);
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        return userFeignService.findUserAddress(param);
    }

    @RequestMapping("/user/info")
    public R userInfo(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        return userFeignService.info(map);
    }

    /**
     * @param params points消耗积分，money要支付的金额（未减去积分前），produceIds（商品id，数组
     * @return
     */
    @Transactional
    @RequestMapping("/pay")
    public synchronized R pay(@RequestBody Map<String, Object> params, HttpSession session) {
        //消耗积分: 0.0
        double points = Double.valueOf(params.get("points").toString());
        //需支付金额：67426.0
        double money = Double.valueOf(params.get("money").toString());
        //用户实际支付金额:
        BigDecimal pay=new BigDecimal(params.get("userMoney").toString());
        //address:2
        Integer addressId = Integer.valueOf(params.get("addressId").toString());
        //produceIds： [{produceId=2, produce_quantity=1}, {produceId=3, produce_quantity=100}, {produceId=4, produce_quantity=10}]
        ArrayList<Map<String, Object>> produceInfo = (ArrayList<Map<String, Object>>) params.get("produceInfo");
        //shoppingCartIds:[10, 11, 12]
        ArrayList<Integer> cids = (ArrayList<Integer>) params.get("shoppingcartIds");
        for (Integer cid:cids)
            System.out.println(cids);

        Map<String, Object> addressInfo = (Map<String, Object>) (userFeignService.info(addressId).get("address"));
        //log.info("addressInfo:"+addressInfo);

        //用户信息
        Integer userId = (Integer) session.getAttribute("userId");

        Map<String, Object> um = new HashMap<>();
        um.put("userId", userId);
        Map<String, Object> info = (Map<String, Object>) (userFeignService.info(um).get("user"));

        //更新用户积分
        UserEntity user=new UserEntity();
        user.setUserId(userId);
        user.setPoints(new BigDecimal(info.get("points").toString()).add(BigDecimal.valueOf(money-points)));

        //根据商品id获取店家id
        //一个商家对应多个商品
        Map<Integer, ProduceInfo> map = new HashMap<>();
        for (Map<String, Object> m : produceInfo) {
            Integer produceId = (Integer) m.get("produceId");
            Integer produceQuantity = (Integer) m.get("produce_quantity");//数量
            //根据id获取店家
            //获得商品信息
            Map<String, Object> pInfo = (Map<String, Object>) (produceFeignService.info(produceId).get("produce"));
            ProduceVo entity = new ProduceVo();
            entity.setProduceId(produceId);
            entity.setProduceName((String) pInfo.get("produceName"));
            entity.setProducePrice(new BigDecimal(pInfo.get("producePrice").toString()));
            entity.setProduceIcon((String) pInfo.get("produceIcon"));
            entity.setProduceStock(((Integer) pInfo.get("produceStock")) - produceQuantity);
            entity.setQuantity(produceQuantity);
            //log.info("id: "+produceId+", 数量:"+produceQuantity+", 单价:"+pInfo.get("producePrice").toString());

            //获取单价
            BigDecimal price = new BigDecimal((String) pInfo.get("producePrice"));
            price = price.multiply(new BigDecimal(produceQuantity));
            //log.info("现在单间商品的价格*数量为:"+price);
            Integer storeId = (Integer) (pInfo).get("storeId");
            if (!map.containsKey(storeId)) {
                ProduceInfo temp = new ProduceInfo();
                List<ProduceVo> list = new ArrayList<>();
                list.add(entity);
                temp.setMount(price);
                temp.setList(list);
                map.put(storeId, temp);
                //map.put(storeId,list);
            } else {
                ProduceInfo temp = map.get(storeId);
                BigDecimal pt = temp.getMount();
                temp.setMount(pt.add(price));
                temp.getList().add(entity);
                //integers.add(produceId);
            }

            //log.info("现在价格："+map.get(storeId).getMount());
        }

        for (Integer store : map.keySet()) {
            OrderEntity orderEntity = new OrderEntity();

            orderEntity.setUserId(userId);
            orderEntity.setStoreId(store);
            orderEntity.setBuyerName(addressInfo.get("firstName").toString() + addressInfo.get("lastName"));
            orderEntity.setBuyerPhone((String) addressInfo.get("phoneNumber"));
            orderEntity.setBuyerAddress(addressInfo.get("area").toString() + addressInfo.get("detailAddress"));
            orderEntity.setPayTime(new Date());
            orderEntity.setOrderAmount(map.get(store).getMount());
            orderEntity.setPayStatus("已支付");
            orderEntity.setOrderStatus("未完成");

            //log.info("创建订单:\n");
            //log.info(orderEntity.toString());
            Map<String, Object> order = (Map<String, Object>)orderFeignService.save(orderEntity).get("order");
            //log.info("新增id看看有没有"+order.get("orderId").toString());

            //log.info("商品信息更新，更新库存，同时更新订单详情OrderDetail:\n");
            for (ProduceVo p : map.get(store).getList()) {
                //log.info(p.toString());
                OrderDetailEntity orderDetailEntity = new OrderDetailEntity();
                orderDetailEntity.setOrderId(Integer.valueOf(order.get("orderId").toString()));
                orderDetailEntity.setProduceId(p.getProduceId());
                orderDetailEntity.setProduceName(p.getProduceName());
                orderDetailEntity.setProducePrice(p.getProducePrice());
                orderDetailEntity.setProduceQuantity(p.getQuantity());
                orderDetailEntity.setProduceIcon(p.getProduceIcon());

                orderFeignService.save(orderDetailEntity);

                //log.info("保存账单细节:");
                //log.info(orderDetailEntity.toString());
                //log.info("更新商品");
                //log.info(p.toString());

                produceFeignService.update(p);
            }
            //创建Bill了
            BillEntity billEntity=new BillEntity();
            billEntity.setAmount(pay);
            billEntity.setCreateTime(new Date());
            billEntity.setIconUrl("?");
            billEntity.setTitle("?");
            billEntity.setOrderId(Integer.valueOf(order.get("orderId").toString()));
            billService.save(billEntity);
        }

        userFeignService.update(user);
        //清空購物車
        shoppingCartFeignService.deleteByFeign(cids.toArray(new Integer[cids.size()]),userId);
        log.info("支付完成");
        return R.ok();
    }

    @Data
    class ProduceInfo {
        private BigDecimal mount;
        private List<ProduceVo> list;
    }
}
